package de.grosjohann.android.feuerwehr;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import de.grosjohann.android.feuerwehr.service.FMSNotificationService;
import de.grosjohann.android.feuerwehr.service.IntentServiceFacade;
import de.grosjohann.android.feuerwehr.service.WeatherNotificationService;

public class PrefsActivity
  extends PreferenceActivity
  implements OnSharedPreferenceChangeListener {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.layout.prefs);
  }

  @Override
  protected void onResume() {
    super.onResume();

    // Set up a listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
  }

  @Override
  protected void onPause() {
    super.onPause();

    // Unregister the listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    final String keyToCheck = getString(R.string.prefKeyInterval);

    if (keyToCheck.endsWith(key)) {
      IntentServiceFacade.restartRepeating(getApplicationContext(), FMSNotificationService.class);
      IntentServiceFacade.restartRepeating(getApplicationContext(), WeatherNotificationService.class);
    }

  }
}